<style scoped>

.extendGroup {
  float: right;
  margin-right: 20px;
  opacity: 0;
}

.el-tree-node__content:hover .extendGroup {
  opacity: 1;
}

</style>

<template>
  <div>
     
      <template v-if="routerPath=='users'" >
        <div v-loading="loading">
         
        <!-- 操作 -->
        <!--工具条-->
        <el-col :span="24" class="toolbar table_toolbar" style="padding-bottom: 0px;">
          <el-form :inline="true" :model="filters">
            <el-form-item class="table_input">
              <el-input v-model="filters.name" placeholder="根据身份证号/姓名/账号/电话号码检索"></el-input>
            </el-form-item>
            <el-form-item class="table_i">
              <el-button type="primary" v-on:click="fetchData"><i class="el-icon-search"></i></el-button>
            </el-form-item>
            <el-form-item class="table_btn_r" >
              <el-button class="table_btn_r" type="primary" v-has="[users.add]" @click="handleAdd">添加用户</el-button>
            </el-form-item>
          </el-form>
        </el-col>
        <div class="operation">
          <!-- <el-button size="small" type="danger" v-has="[users.remove]">删除</el-button> -->

    <!--       <el-button size="small" type="primary" v-has="[role.request]" @click="fetchData">查询</el-button>
          <el-button size="small" type="danger" v-has="[role.remove]">删除</el-button>
          <el-button size="small" v-if="$_has([role.request]) && canReset">重置</el-button>
          <el-button size="small" type="info" @click="requestNotAllowed">尝试发起越权请求</el-button> -->

        </div>
        <!-- table start  -->
        <el-table :data="list" border style="width: 100%">
          <el-table-column prop="loginName" label="账号" width="120">
          </el-table-column>
          <el-table-column prop="userName" label="姓名">
          </el-table-column>
          <el-table-column prop="nickName" label="昵称">
          </el-table-column>
          <el-table-column prop="userGender" label="性别"  :formatter="formatSex">
          </el-table-column>
          <el-table-column prop="certNo" label="身份证号">
          </el-table-column>
          <el-table-column prop="userMail" label="邮箱">
          </el-table-column>
          <el-table-column prop="phoneNum" label="电话">
          </el-table-column>
          <el-table-column prop="groupList" label="用户所在组">
            <template slot-scope="scope">
             <!--  <span class=" span_block" @click="toGroup"><i class="dot"></i><span>组1</span></span>
              <span class=" span_block" @click="toGroup"><i class="dot"></i><span>组2</span></span> -->
              <!-- <span class=" span_block" v-for="item in scope.row.groupList"><i class="dot"></i><span>{{item.groupName}}</span></span> -->
              <span  class="span_block" v-for="(item,index) in scope.row.groupList" v-show="index< scope.row.showIndexG"><i class="dot"></i><span>{{item.groupName}}</span></span>             
              <span class="more" @click="toggleHG(scope.$index, scope.row)" v-if="scope.row.showIndexG==2  && scope.row.groupList.length>2">+</span>
              <span class="more" @click="toggleHGC(scope.$index, scope.row)" v-if="scope.row.showCloseG">-</span>

            </template>
          </el-table-column>
          <el-table-column prop="roleList" label="角色">
            <template slot-scope="scope">
             <!--  <span class=" span_block" @click="toGroup"><i class="dot"></i><span>组1</span></span>
              <span class=" span_block" @click="toGroup"><i class="dot"></i><span>组2</span></span> -->
            
              <span  class="span_block" v-for="(item,index) in scope.row.roleList" v-show="index< scope.row.showIndex"><span>{{item.roleName}}</span></span>             
              <span class="more" @click="toggleH(scope.$index, scope.row)" v-if="scope.row.showIndex==2  && scope.row.roleList.length>2">+</span>
              <span class="more" @click="toggleHC(scope.$index, scope.row)" v-if="scope.row.showClose">-</span>

      
            </template>
          </el-table-column>
          <el-table-column label="操作" width="280" align="center">
            <template slot-scope="scope">
            <!--   <el-button size="mini" type="info">编辑</el-button>
              <el-button size="mini" type="danger">删除</el-button> -->
              <span class="span_btn" v-if="isReleRole"  @click="releRoles(scope.$index, scope.row)">关联角色</span>
              <span class="span_line" v-if="isReleRole && isReleGroup">|</span>
              <span class="span_btn" v-if="isReleGroup"   @click="releGroup(scope.$index, scope.row)">关联分组</span>
              <span class="span_line" v-if="isReleGroup && isEdit" >|</span>
              <span class="span_btn" v-if="isEdit"  @click="handleEdit(scope.$index, scope.row)" >编辑</span>
              <span class="span_line" v-if="isEdit && isDel" >|</span>
              <span class="span_btn span_btn_del" v-if="isDel"  @click="handleDel(scope.$index, scope.row)" >删除</span>

            </template>
          </el-table-column>
        </el-table>
          <!--工具条-->
        <el-col :span="24" class="toolbar toolbar_footer">
          <el-pagination v-if="total" background layout="prev, pager, next,total,jumper" @current-change="handleCurrentChange" :page-size="showCount" :total="total" style="float:right;">
          </el-pagination>
        </el-col>
        <!-- table end  -->
        <!-- 新增页面 -->
         <el-dialog title="添加用户" class="form_part" :visible.sync="addFormVisible"  :close-on-click-modal="false">
          <el-form :model="addForm" label-width="83px" :rules="addFormRules" ref="addForm">
            <div class="form_left">
              <el-form-item label="姓名:" prop="userName">
                <el-input v-model="addForm.userName" auto-complete="off"></el-input>
              </el-form-item>
              <el-form-item label="昵称:" prop="nickName">
                <el-input v-model="addForm.nickName" auto-complete="off"></el-input>
              </el-form-item>              
              <el-form-item label="账号:" prop="loginName">
                <el-input v-model="addForm.loginName" auto-complete="off"></el-input>
              </el-form-item>
                <el-form-item label="密码:" prop="loginPass">
                <el-input v-model="addForm.loginPass" auto-complete="off"></el-input>
              </el-form-item>

            </div>
            <div class="form_right">
               <el-form-item label="性别:" prop="userGender">
                <el-radio-group v-model="addForm.userGender">
                  <el-radio class="radio" :label="1">男</el-radio>
                  <el-radio class="radio" :label="2">女</el-radio>
                </el-radio-group>
              </el-form-item>
                <el-form-item label="手机号:" prop="phoneNum">
                <el-input v-model="addForm.phoneNum" auto-complete="off"></el-input>
              </el-form-item>
             
              <el-form-item label="邮箱:" prop="userMail">
                <el-input v-model="addForm.userMail" auto-complete="off"></el-input>
              </el-form-item>
              <el-form-item label="身份证号:" prop="certNo">
                <el-input v-model="addForm.certNo" auto-complete="off"></el-input>
              </el-form-item>
            </div>
           
            
            <!-- <el-form-item label="年龄">
              <el-input-number v-model="addForm.age" :min="0" :max="200"></el-input-number>
            </el-form-item>
            <el-form-item label="生日">
              <el-date-picker type="date" placeholder="选择日期" v-model="addForm.birth"></el-date-picker>
            </el-form-item>
            <el-form-item label="地址">
              <el-input type="textarea" v-model="addForm.addr"></el-input>
            </el-form-item> -->
          </el-form>
          <div slot="footer" class="dialog-footer">
            <!-- <el-button @click.native="addFormVisible = false">取消</el-button> -->
            <el-button type="primary" v-has="[users.add]" @click.native="addSubmit('addForm')" :loading="addLoading">保存</el-button>
          </div>
        </el-dialog>

         <!-- 编辑页面 -->
         <el-dialog title="编辑用户" class="form_part" :visible.sync="editFormVisible"  :close-on-click-modal="false">
          <el-form :model="editForm" label-width="83px" :rules="editFormRules" ref="editForm">
            <div class="form_left">
              <el-form-item label="姓名:" prop="userName">
                <el-input v-model="editForm.userName" auto-complete="off"></el-input>
              </el-form-item>
               
              <el-form-item label="昵称:" prop="nickName">
                <el-input v-model="editForm.nickName" auto-complete="off"></el-input>
              </el-form-item>              
              <el-form-item label="账号:" prop="loginName">
                <el-input v-model="editForm.loginName" auto-complete="off" disabled></el-input>
              </el-form-item>
                <el-form-item label="密码:" prop="loginPass">
                <el-input v-model="editForm.loginPass" auto-complete="off" disabled></el-input>
              </el-form-item>
  
            </div>
            <div class="form_right">
              <el-form-item label="性别:" prop="userGender">
                <el-radio-group v-model="editForm.userGender">
                  <el-radio class="radio" :label="1">男</el-radio>
                  <el-radio class="radio" :label="2">女</el-radio>
                </el-radio-group>
              </el-form-item>
               <el-form-item label="手机号:" prop="phoneNum">
                <el-input v-model="editForm.phoneNum" auto-complete="off"></el-input>
              </el-form-item>
              <el-form-item label="邮箱:" prop="userMail">
                <el-input v-model="editForm.userMail" auto-complete="off"></el-input>
              </el-form-item>
              <el-form-item label="身份证号:" prop="certNo">
                <el-input v-model="editForm.certNo" auto-complete="off"></el-input>
              </el-form-item>
            </div>
 
          </el-form>
          <div slot="footer" class="dialog-footer">
            <!-- <el-button @click.native="addFormVisible = false">取消</el-button> -->
            <el-button type="primary" @click.native="editSubmit('editForm')" :loading="editLoading">保存</el-button>
          </div>
        </el-dialog>
      </div>
      </template>
       <template v-else>
        <router-view></router-view>
      </template>
  </div>

  
  
</template>

<script>
import * as users from '../api/users';
import isvalidPhone from '../api/valide';
import qs from 'qs';
import md5 from 'js-md5';

let myMixin = {
  data: function() {
    return { users }
  }
}
var validPhone=(rule, value,callback)=>{
      if (!value){
          callback(new Error('请输入电话号码'))
      }else  if (!isvalidPhone.isvalidPhone(value)){
        callback(new Error('请输入正确的11位手机号码'))
      }else {
          callback()
      }
  }
export default {
  mixins: [myMixin],
  data() {
    return {
      isDel:true,
      isEdit:true,
      isReleRole:true,
      isReleGroup:true,
      total: 10,
      page: 1,
      showCount:10,
      routerPath:'',
      filters:{name:''},//搜索表单
      addFormVisible:false,//新增页面是否显示,
      editFormVisible:false,//编辑界面是否显示
      addForm:{userGender:1},//新增页面数据
      editForm:{},//编辑页面数据
      addFormRules:{
        userName: [
            { required: true, message: '请输入姓名', trigger: 'blur' }
          ],
        userGender: [
          { required: true, message: '请选择性别', trigger: 'blur' }
        ],
        loginName: [
          { required: true, message: '请输入账号', trigger: 'blur' }
        ],
        loginPass: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        phoneNum: [
          // { required: true, message: '请输入手机号', trigger: 'blur' }
          { required: true, trigger: 'blur', validator:validPhone }//这里需要用到全局变量

        ],
        userMail: [
          { required: true, message: '请输入邮箱', trigger: 'blur' }
        ],
        certNo: [
          { required: true, message: '请输入身份证号', trigger: 'blur' }
        ]
      },
      editFormRules:{
        userName: [
            { required: true, message: '请输入姓名', trigger: 'blur' }
          ],
        userGender: [
          { required: true, message: '请选择性别', trigger: 'blur' }
        ],
        loginName: [
          { required: true, message: '请输入账号', trigger: 'blur' }
        ],
         loginPass: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        phoneNum: [
          { required: true, message: '请输入手机号', trigger: 'blur' }
        ],
        userMail: [
          { required: true, message: '请输入邮箱', trigger: 'blur' }
        ],
        certNo: [
          { required: true, message: '请输入身份证号', trigger: 'blur' }
        ]
      },
      addLoading:false,//
      editLoading:false,//
      list: [],
      canReset: true,
      loading: false,
      groupId:'',//组id
      userId:''//用户id
    }
  },
  methods: {
    toggleHG(index,row){
      this.$set(this.list[index],'showIndexG',row.groupList.length)
      this.$set(this.list[index],'showCloseG',true);


    },
    toggleH(index,row){
      this.$set(this.list[index],'showClose',true);
      this.$set(this.list[index],'showIndex',row.roleList.length)
    },
   toggleHGC(index,row){
      this.$set(this.list[index],'showIndexG',2)
      this.$set(this.list[index],'showCloseG',false);


    },
    toggleHC(index,row){
      this.$set(this.list[index],'showClose',false);
      this.$set(this.list[index],'showIndex',2)
    },
    //性别显示转换
    formatSex: function (row, column) {
      return row.userGender == 1 ? '男' : row.userGender == 2 ? '女' : '未知';
    },
    handleCurrentChange(val) {
      this.page = val;
      // this.getUsers();
      this.fetchData();
    },
    releGroup(index,row){
      //关联分组
      this.routerPath='relegroup';
         this.$router.push({path:'/authlist/users/relegroup',query: {id: row.userId}})

    },
     releRoles(index,row){
      //关联角色
      this.routerPath='releroles';
       this.$router.push({path:'/authlist/users/releroles',query: {id: row.userId}})
    },
    toGroup(){
      //查看用户组管理
      // this.$router.push('/authlist/usergroup')

    },
    getUsers(){
      //获取用户列表数据
    },
    //显示编辑界面
    handleEdit: function (index, row) {
      this.editFormVisible = true;
      this.userId=row.userId;
        let para={
        userId:row.userId
       }
        users.info.r(para).then((res) => {
          if(res.data.retCode==1){
              this.editForm=res.data.data;
              this.editForm.loginPass="***";
              

          }else{
            this.$message(res.data.retMsg);
          }              
      })
    },
    //显示新增界面
    handleAdd: function () {
      // this.$router.push({path:"/add"});
     this.addFormVisible = true;
    
    },
    addSubmit:function(){
      //新增数据提交
        this.$refs.addForm.validate((valid) => {
          if (valid) {
             let para = {
              nickName:this.addForm.nickName,
              userName:this.addForm.userName,

              loginName:this.addForm.loginName,
              loginPass:md5('STARSAND_' + this.addForm.loginPass),
              userMail:this.addForm.userMail,
              phoneNum:this.addForm.phoneNum,
              certNo:this.addForm.certNo,
              userGender:this.addForm.userGender.toString()
           
            };
            // console.log(qs.stringify(para));
            // return;
            users.add.r(para).then((res) => {
              if(res.data.retCode==1){
                //添加用户成功
                this.addFormVisible = false;

                this.fetchData();
              }else{
                this.$message(res.data.retMsg);
              }
              
            });
          }else{
            console.log('error submit!!');
            return false;
          }
        })

    },
    editSubmit:function(){
      //编辑数据提交
      this.$refs.editForm.validate((valid) => {
          if (valid) {
             let para = {
              userId:this.userId,
              nickName:this.editForm.nickName,
              userName:this.editForm.userName,

              loginName:this.editForm.loginName,
              // loginPass:this.editForm.loginPass,
              userMail:this.editForm.userMail,
              phoneNum:this.editForm.phoneNum,
              certNo:this.editForm.certNo,
              userGender:this.editForm.userGender.toString()
           
            };
            // console.log(qs.stringify(para));
            // return;
            users.modify.r(para).then((res) => {
              if(res.data.retCode==1){
                //编辑用户成功
                this.editFormVisible = false;

                this.fetchData();
              }else{
                this.$message(res.data.retMsg);
              }
              
            });
          }else{
            console.log('error submit!!');
            return false;
          }
      })
    },
    //删除
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        //NProgress.start();
        let para = { id: row.userId };
        users.remove.r(para).then((res) => {
            if(res.data.retCode==1){
              //删除成功
              this.$message('删除成功');


              this.fetchData();
            }else{
              this.$message(res.data.retMsg);
            }
            
        });
        
      }).catch(() => {

      });
    },
    fetchData(init) {
      this.loading = true;
      if(!this.$_has([users.request])){
        this.$message("暂无权限");
        this.loading = false;

        return;
      }
      let para = {
          // groupId:this.groupId,
          showCount:this.showCount,
          currentPage:this.page,//当前查询页
          keyword:this.filters.name
        };
        if(this.groupId!=undefined&&this.groupId!="undefined"&&this.groupId!=""){
          this.$set(para,'groupId',this.groupId)
        }
      users.request.r(para).then((res) => {
        this.total=res.data.data.totalRow;
        this.list = res.data.data.list;
        
        if(this.list!=null){
          this.list.map(x=>{
            this.$set(x,'showIndex',2)  
            this.$set(x,'showClose',false)       
            this.$set(x,'showCloseG',false)       
            this.$set(x,'showIndexG',2)         
          })
        }

        this.loading = false;
      });
    },
    requestNotAllowed: function(){
      users.notAllowed.r();
    }
  },
  watch: {
          // 如果路由有变化，会再次执行该方法
          "$route": function(){
            this.routerPath=this.$route.path.split("/").pop();
            this.groupId="";
            this.fetchData(true)

          }
  },
  created() {
   /* this.isReleRole=this.$_has([users.releRolesUser]);
    this.isReleGroup=this.$_has([users.releGroupUser]);
    this.isEdit=this.$_has([users.modify]);
    this.isDel=this.$_has([users.remove]);
    if(this.$route.query.groupId!=undefined&&this.$route.query.groupId!="undefined"&&this.$route.query.groupId!=""){
      this.groupId=this.$route.query.groupId;
    }

    this.fetchData(true)*/
    /*console.log(this.$route.path.split("/").pop())*/
    
    this.routerPath=this.$route.path.split("/").pop();

  }
}
</script>